<?php
/**
 * Created by PhpStorm.
 * User: Ling
 * Date: 5/27/15
 * Time: 21:09
 */

/**
 * Class RSA
 * RSA 非对称加解密类
 */
class RSA {
    /**
     * @var resource $pubKey, $priKey 公钥资源对象和私钥资源对象
     *
     */
    private $pubKey, $priKey;

    /**
     * 构造函数, 初始化整个类
     * @param $pub 公钥文件地址
     * @param $pri 私钥文件地址
     * @throws Exception 如果读取文件报错, 抛出相应异常
     */
    function __construct($pub, $pri) {
        try{
            $pubKeyStr = file_get_contents($pub);
        }catch(Exception $e){
            throw new Exception("找不到公钥文件");
        }
        try{
            $priKeyStr = file_get_contents($pri);
        }catch(Exception $e){
            throw new Exception("找不到私钥文件");
        }
        $this->pubKey = openssl_pkey_get_public($pubKeyStr);
        $this->priKey = openssl_pkey_get_private($priKeyStr);
    }

    /**
     * @param $data 需要被加密的字符串
     * @return string 返回公钥加密之后的字符串
     */
    public function pubKeyEncrypt($data) {
        $encrypted = '';
        openssl_public_encrypt($data, $encrypted, $this->pubKey);
        return base64_encode($encrypted);
    }

    /**
     * @param $data 需要被加密的字符串
     * @return string 返回私钥加密之后的字符串
     */
    public function priKeyEncrypt($data) {
        $encrypted = '';
        openssl_private_encrypt($data, $encrypted, $this->priKey);
        return base64_encode($encrypted);
    }

    /**
     * @param $data 需要被解密的字符串
     * @return string 返回私钥解密之后的字符串
     */
    public function priKeyDecrypt($data) {
        $decrypted = '';
        openssl_private_decrypt(base64_decode($data), $decrypted, $this->priKey);
        return $decrypted;
    }

    /**
     * @param $data 需要被解密的字符串
     * @return string 返回公钥解密之后的字符串
     */
    public function pubKeyDecrypt($data) {
        $decrypted = '';
        openssl_public_decrypt(base64_decode($data), $decrypted, $this->pubKey);
        return $decrypted;
    }
}